import React, { FC } from 'react';
import { Form, Input, message } from 'antd';
import { connect } from 'dva';
import { Dispatch } from 'redux';
import { ModalProps } from 'antd/lib/modal';
import { FormComponentProps } from 'antd/lib/form';
import CommonModal from '@/components/Modal/CommonModal';
import VerficationInput from '@/components/Input/VerificationInput';
import ConnectState from '@/models/connect';
import { IModifyPasswordParams, ISysUserAdmin } from '@/services/login';
import { IUserInfo } from '@/services/login';
import { validateLength } from '@/utils/validator';

const FormItem = Form.Item;

const { Password } = Input;

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};

interface IModifyPasswordProps extends FormComponentProps, ModalProps {
  status: boolean;
  userInfo: IUserInfo;
  onCancel: () => void;
  updatePassword: (params: IModifyPasswordParams) => Promise<any>;
  getCode: (phone: string) => Promise<any>;
}

const ModifyPassword: FC<IModifyPasswordProps> = props => {
  const {
    form: { getFieldDecorator, validateFields },
    status,
    userInfo: { sysUserAdmin = {} as ISysUserAdmin },
    getCode,
    updatePassword,
    onCancel,
  } = props;

  const getVerifyCode = () => {
    const phone = sysUserAdmin.phone;

    if (!phone) {
      message.error('无法获取用户的手机号');
      return;
    }

    getCode(phone);
  };

  const handleSumbit = () => {
    validateFields((err, values) => {
      if (!err) {
        const { password, confirmPassword } = values;

        if (password !== confirmPassword) {
          message.error('前后两次密码不一致，请仔细确认!');
          return;
        }

        const newData = { ...values, adminUserCode: sysUserAdmin.userCode };

        delete newData.account;
        delete newData.confirmPassword;

        updatePassword(newData).then(() => {
          onCancel();
        });
      }
    });
  };

  return (
    <CommonModal visible={status} title="修改密码" onOk={handleSumbit} onCancel={onCancel}>
      <Form {...formItemLayout}>
        <FormItem label="用户账号">
          {getFieldDecorator('account', {
            rules: [{ required: true, message: '请输入账号' }],
          })(<Input disabled />)}
        </FormItem>
        <FormItem label="验证码">
          {getFieldDecorator('smsCode', {
            rules: [{ required: true, message: '请输入验证码' }],
          })(<VerficationInput getVerifyCode={getVerifyCode} />)}
        </FormItem>
        <FormItem label="输入密码">
          {getFieldDecorator('password', {
            rules: [
              { required: true, message: '请输入密码' },
              { validator: validateLength('密码', 6) },
            ],
          })(<Password placeholder="设置6至20位登录密码" maxLength={20} />)}
        </FormItem>
        <FormItem label="确认密码">
          {getFieldDecorator('confirmPassword', {
            rules: [
              { required: true, message: '请输入确认密码' },
              { validator: validateLength('密码', 6) },
            ],
          })(<Password placeholder="请再次输入登录密码" maxLength={20} />)}
        </FormItem>
      </Form>
    </CommonModal>
  );
};

const WrappedModifyPassword = Form.create<IModifyPasswordProps>({
  mapPropsToFields(props) {
    const { sysUserAdmin = {} as ISysUserAdmin } = props.userInfo;

    return {
      account: Form.createFormField({
        value: sysUserAdmin.name || '',
      }),
    };
  },
})(ModifyPassword);

const mapStateToProps = ({ login }: ConnectState) => {
  const { userInfo = {} } = login;

  return { userInfo };
};

const mapDispatchToProps = (dispatch: Dispatch) => {
  const namespace = 'login';

  return {
    getCode: (phone: string) => dispatch({ type: `${namespace}/getVerifyCode`, payload: phone }),
    updatePassword: (params: IModifyPasswordParams) =>
      dispatch({ type: `${namespace}/updatePassword`, payload: params }),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(WrappedModifyPassword);
